var formData = {
    username : '',
    mobile : '',
    code : '',
    sex : '保密',
    company : '',
    job : '',
    email : '',
    industry : '',
    ispush: ['1']
}

var app = new Vue({
    el: '#body',

    data (){
        return {
            aid : $config.GetQueryString('aid'),
            type : $config.GetQueryString('type'),
            isShow : false, //有多个值，signUp报名，signIn签到
            detail: '',
            code : '',
            forms: '',
            tickets : '',
            text : '获取验证码',
            redirect : '',
            btnlock : false,     //是否禁用获取验证码的按钮
            imgs :[],   //上传的图片
            isqrcodeShow : false,
            qrcode : '',
            qrIndex : '',
            //埋点数据
            dataPoint : {
                id : $config.GetQueryString('aid'),
                module : 'h5Activity',
                sign : '' //分享签名
            }
        }
    },
    mounted() {
        this.getData();

        //页面浏览埋点
        this.common().buryPoint(this.dataPoint,{
            type : 'browse',
            data : {
                fromShareSignId : $config.GetQueryString('sharesign') || ''
            }
        })
    },
    methods :{
        // 获取页面数据
        getData (){
            this.common().http(this, {
                url: '/Event/detail',
                body: {
                    id : this.aid
                },
                success(json) {
                    this.detail = json.data;
                    //显示页面
                    if(this.type){
                        this.checkout(this.type,true);
                    }else{
                        this.checkout(true);
                    }

                    // 设置标题
                    document.title = json.data.title;

                    //微信分享-埋点签名
                    let _this = this;
                    this.common().getShareSign.call(this,{
                        item:{activityId:_this.aid},
                        success (){
                            var sign = _this.dataPoint.sign || '';
                            //分享设置
                            $config.wxShare({
                                title : json.data.share_title,
                                cont : json.data.share_desc,
                                logo : json.data.share_img,
                                url : `${location.href.split('?')[0]}?aid=${$config.GetQueryString('aid')}&sharesign=${sign}`,
                                success (){
                                    //分享成功埋点
                                    _this.common().buryPoint(_this.dataPoint,{
                                        type : 'share',
                                        data : {
                                            shareSignId : sign
                                        }
                                    })
                                }
                            });
                        }
                    })
                }
            });
        },
        // 切换选择
        checkout (value,type){
            if(value=='signUp' || value=='signIn'){
                if($config.wxVerify('&type='+value)){
                    this.isShow = value;
                    if(value=='signUp'){
                        this.getForm();
                    }else if(value=='signIn'){
                        this.getMyTicket();
                    }
                }
            }else{
                this.isShow = value;
            }
        },
        //签到活动
        signIn (apply_id,index){
            this.common().http(this, {
                lock : true,
                url: '/Event/signIn',
                body: {
                    apply_id
                },
                success(json) {
                    console.log(json)
                    this.tickets.apply_list[index].status = 0;
                }
            });
        },
        // 活动表单
        getForm (){
            if(this.forms) {
                $config.toScrollElement('.scroll');
                return;
            };
            this.common().http(this, {
                url: '/Event/form',
                body: {
                    id : this.aid
                },
                success(json) {
                    this.forms = json.data;
                    //初始化
                    this.initGt();

                    let data = this.forms;
                    data.forEach((item)=>{
                        if(item.fieldname == 'sex'){
                            item.value = '保密';
                        }else if(item.type == 'checkbox'){
                            item.value = [];
                        }else if(item.type == 'select'){
                            item.value = '';
                        }

                        //如果有图片要上传的时候
                        if(item.type == 'file'){

                        }
                    })

                    $config.toScrollElement('.scroll');
                }
            });
        },
        // 我的入场券
        getMyTicket (){
            if(this.tickets) {
                $config.toScrollElement('.scroll');
                return;
            };
            this.common().http(this, {
                url: '/Event/ticket',
                body: {
                    id : this.aid
                },
                success(json) {
                    let tickets = json.data;
                    if(tickets.apply_list.length > 0){
                        this.tickets = tickets;
                    }else{
                        this.tickets = 'no';
                    }

                    $config.toScrollElement('.scroll');
                }
            });
        },
        //提交报名
        submit (){
            // 必填
            let forms = this.forms,
                body = {
                    id : this.aid,
                    code : this.code
                };
            // 校验
            for(let item of forms){
                //必填选项，并且为空值的时候
                if(item.required==1){
                    //图片校验
                    if(item.type == 'file'){
                        if(this.imgs.length == 0){
                            swal({
                                title: '请上传照片',
                                type: "warning"
                            });
                            return;
                        }else{
                            if(!this.imgs[0].loaded){
                                swal({
                                    title: '图片正在上传',
                                    type: "warning"
                                });
                                return;
                            }
                        }
                    }
                    else if(item.type == 'checkbox'){
                        if(item.value.length == 0){
                            swal({
                                title: `请输入${item.label}`,
                                type: "warning"
                            });
                            return;
                        }
                    }
                    else{
                        if(!item.value){
                            swal({
                                title: `请输入${item.label}`,
                                type: "warning"
                            });
                            return;
                        }
                    }

                }
            }

            // 赋值
            for(let item of forms){
                let imgs = this.imgs;
                if(item.type == 'file' && imgs.length > 0){
                    body[item.fieldname] = imgs[0].url;
                }else{
                    body[item.fieldname] = item.value || '';
                }
            }

            //请求报名接口
            this.common().http(this, {
                url: '/Event/apply',
                body: body,
                success(json) {
                    //埋点-活动报名成功
                    this.common().buryPoint(this.dataPoint,{
                        type : 'signUp'
                    });

                    swal({
                        title: '报名成功',
                        type: "success"
                    },()=>{
                        this.checkout(true);
                        this.forms = '';
                        location.href = json.data.url;
                    });
                }
            });
        },
        //极验初始化
        initGt() {
            this.common().http(this, {
                allow : true,
                type: 'get',
                url: '/Users/StartCaptchaServlet3',
                success(json) {
                    var data = json;
                    initGeetest({
                        // 以下配置参数来自服务端 SDK
                        gt: data.gt,
                        challenge: data.challenge,
                        offline: !data.success,
                        new_captcha: data.new_captcha,
                        product: 'bind'
                    }, (captchaObj) => {
                        // 这里可以调用验证实例 captchaObj 的实例方法
                        document.getElementById('btn').addEventListener('click', () => {
                            //如果有锁就禁止
                            if (this.btnlock) return;
                            //校验
                            if ($config.rex.mobile.test(this.formValue('mobile'))) {
                                captchaObj.verify();
                            } else {
                                swal({
                                    title: "请输入正确的手机号",
                                    type: "warning"
                                });
                            }
                        });

                        //验证成功
                        captchaObj.onSuccess(() => {
                            var result = captchaObj.getValidate();
                            // ajax 伪代码，进行二次验证
                            this.common().http(this, {
                                url: '/Users/VerifyLoginServlet3',
                                body: {
                                    action : 'event',
                                    event_id: this.aid,
                                    mobile: this.formValue('mobile'),
                                    geetest_challenge: result.geetest_challenge,
                                    geetest_validate: result.geetest_validate,
                                    geetest_seccode: result.geetest_seccode
                                    // 其他服务端需要的数据，比如登录时的用户名和密码
                                },
                                success(json) {
                                    // 根据服务端二次验证的结果进行跳转等操作
                                    this.countdown();
                                }
                            });
                        });
                    })
                }
            });
        },
        //倒计时
        countdown(){
            var num = 60,
                time = setInterval(()=>{
                    num--;
                    if(num>0){
                        this.text = num+'秒';
                    }else{
                        this.btnlock = false;
                        this.text = '重新获取';
                        clearInterval(time);
                    }
                },1000);
            this.btnlock = true;
            this.text = num+'秒';
        },
        //值计算
        formValue(name){
            let forms = this.forms;
            for(let item in forms){
                if(forms[item].fieldname == name){
                    return forms[item].value;
                }
            }
        },
        //微信选择图片
        chooseImage() {
            var _this = this,
                crrunt = 0,
                total,
                localIds,
                uploadImage = () => {
                    wx.uploadImage({
                        localId: localIds[crrunt], // 需要上传的图片的本地ID，由chooseImage接口获得
                        isShowProgressTips: 0, // 默认为1，显示进度提示
                        success: function (res) {
                            var serverId = res.serverId; // 返回图片的服务器端ID
                            _this.wxUploadImg(localIds[crrunt], serverId);
                            crrunt++;
                            if (crrunt < total) {
                                uploadImage()
                            }

                        }
                    });
                };
            wx.chooseImage({
                count: 1, // 默认1
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有

                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: function (res) {
                    localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                    total = localIds.length;
                    //设置只有一张图片
                    _this.imgs = [];
                    for (var value of localIds) {
                        _this.imgs.push({
                            localId: value,
                            url: value,
                            loaded: false
                        })
                    }
                    uploadImage();
                }
            });
        },
        //微信上传图片
        wxUploadImg(lid, sid) {
            this.$http.post('http://upfile.kcis.cn/wxPic.php?m=WXPic&a=localizePic&config_key=yxq', {
                localId: lid,
                mediaId: sid
            }).then(res => {
                var json = res.body;
                for (var value of this.imgs) {
                    if (value.localId == json.localId) {
                        value.loaded = true;
                        value.url = json.url;
                    }
                }
            });
        },
        //打开二维码
        openQrcode(index){
            let ticket = this.tickets.apply_list[index];
            this.qrIndex = index;
            this.isqrcodeShow = true;
            if(!ticket.qrcode){
                this.common().http(this,{
                    url : '/Event/qrcode',
                    body:{
                        apply_id : ticket.apply_id
                    },
                    success(json){
                        this.qrcode = json.data.qrcode;
                    }
                })
            }
        },
        closeQrcode(){
            this.isqrcodeShow = false;
        }
    },
    computed: {
        isfooter () {
            let [isShow,value] = [this.isShow];
            if(isShow != 'signUp' && isShow != 'signIn'){
                value = true;
            }else{
                value = false
            }
            return value;
        }
    }
})